var Common = {
	RUNTIME: {
		IsDebug: false,
		PagerCount: 0,
		RequestCompleted: true,
		ShowLoading: true,
		LoaddingText: '',
		IgnoreVersion: false //访问忽略版本检测
	},
	USERINFO:{},
	init:function(){
		//获取用户数据
		uni.getStorage({
			key: 'USERINFO',
			success: function(res) {
				if(res.data){
					try{
						Common.USERINFO = JSON.parse(res.data);
					}catch(e){
						//出错，重新获取
						console.log(e)
					}
				}
			}
		});
	},
	Config: {
		Server: 'http://gdxfwap2.119cp.cn/',
		ServerPath: 'http://gdxfwap2.119cp.cn/api/',
	},
	guid: function() {
		return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			var r = Math.random() * 16 | 0,
				v = c == 'x' ? r : (r & 0x3 | 0x8);
			return v.toString(16);
		});
	},
	showErrorFun: function(data) { //接口出错提示设置
		if (!data) {
			Common.toast('获取出错,请重试.');
			return;
		}
		let msg = data.Message?data.Message:"服务器出错，请稍后重试!";
		uni.showModal({
			title: '前方出现错误',
			content: msg,
			showCancel:false,
		});
	},
	getClientIdAndOS: function() {
		var data = {};
		try {
			var ClientInfo = plus.push.getClientInfo()
			data.ClientId = ClientInfo.clientid;

			if (plus.os.name == "Android") {
				data.MobileType = 'android';
			} else {
				data.MobileType = 'ios';
				data.ClientId = ClientInfo.clientid;
			}
		} catch (err) {
			data.MobileType = "pc";
			data.ClientId = "";
		}

		return data;
	},
	Valid: {
		getResult: function(validate, value, param) {
			if (!Common.Valid[validate].validator(value, param)) {
				Common.tipMsg(Common.Valid[validate].message);
				return true;
			}
			return false;
		},
		//移动手机号码验证
		mobile: {
			validator: function(value) {
				var reg = /^1[3|4|5|7|8|9]\d{9}$/;
				return reg.test(value);
			},
			message: '输入手机号码格式不正确.'
		},
		email: {
			validator: function(value) {
				var reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
				return reg.test(value);
			},
			message: '输入邮箱格式不正确.'
		},
		qq: {
			validator: function(value) {
				var reg = /^\d{6,10}$/;
				return reg.test(value);
			},
			message: '输入QQ号码格式不正确.'
		},
		less: {
			validator: function(value, param) {
				validateBox.less.message = param.message;
				var length = param.length;
				return value.length >= length;
			}
		},
		equal: {
			validator: function(value, param) {
				validateBox.equal.message = param.message;
				var equalId = param.equalId
				return value == $(equalId).val();
			}
		},
		num: {
			validator: function(value) {
				var reg = /^[0-9]*$/;
				return reg.test(value);
			},
			message: '输入数字格式不正确.'
		}
	},
	_xhrError: function(json, status, textStatus, errorThrown, errorFun) {
		console.log(JSON.stringify(json));
		console.log(status);
		var errorMsg = '',
			_errorMsg = "获取数据失败,请重新尝试";
		if (json && json.hasOwnProperty("Message")) {
			if (json.Message != "" && json.Message != null) errorMsg = json.Message.replace(/\r\n/g, "<br />");
		} else {
			errorMsg = _errorMsg;
		}

		Common.loading.hide();
		Common.RUNTIME.RequestCompleted = true;

		switch (status) {
			case 500:
				errorMsg = _errorMsg;
				break;
			case 401:
				errorMsg = "您还未登录";
				Common.tipMsg(errorMsg, "温馨提示", function() {
					setTimeout(function() {
						var to_url = location.href.replace(new RegExp("\\&", "g"), "|").replace(new RegExp("\\=", "g"), "+");
						Common.logOut();
					}, 50)
				});
				return;
				break;
			case 404:

				errorMsg = "您浏览的内容不存在";
				Common.tipMsg(errorMsg, "温馨提示", function() {
					mui.back();
				});
				return;
				break;

			default:
				break;
		}
		if (json && json.code == 1005) {
			Common.tipMsg("您还未登录", "温馨提示", function() {
				setTimeout(function() {
					var to_url = location.href.replace(new RegExp("\\&", "g"), "|").replace(new RegExp("\\=", "g"), "+");
					Common.logOut();
				}, 50)
			});
			return;
		}

		window.setTimeout(function() {
			if (errorFun) {
				errorFun(json);
			} else {
				Common.tipMsg(errorMsg);
			}
		}, 10);
	},
	_xhrAbort: function() {
		try {
			if (Common.xhr) {
				if (Common.xhr.readyState != 4) {
					Common.xhr.abort();
				}
				Common.xhr = null;
			}

			/*if (Common.RUNTIME.IsDebug) {
			    Common.tipMsg("Common.xhr.abort()", "调试信息");
			}*/
		} catch (e) {
			Common.tipMsg(e.message + '-_xhrAbort', "温馨提示");
		}
	},
	downWgt: function(wgtUrl) {
		var isDownloadingNewApp = Common.getlocalStorage('isDownloadingNewApp');
		if (isDownloadingNewApp == "1" || isDownloadingNewApp == 1) {
			return;
		}
		Common.setlocalStorage('isDownloadingNewApp', 1); //设置正在下载的标志
		mui.toast('正在下载更新文件...');
		plus.downloader.createDownload(wgtUrl, {
			filename: "_doc/update/"
		}, function(d, status) {
			if (status == 200) {
				console.log("下载wgt成功：" + d.filename);
				Common.installWgt(d.filename); // 安装wgt包  
			} else {
				console.log("下载wgt失败！");
				mui.toast('更新文件下载失败!');
				Common.setlocalStorage('isDownloadingNewApp', null); //设置正在下载的标志
			}
		}).start();
	},
	installWgt: function(path) { // 更新应用资源 
		mui.toast('正在安装更新文件');
		plus.runtime.install(path, {}, function() {
			console.log("安装wgt文件成功！");
			mui.toast("应用资源更新完成！");
			Common.setlocalStorage('isDownloadingNewApp', null); //设置正在下载的标志
		}, function(e) {
			console.log("安装wgt文件失败[" + e.code + "]：" + e.message);
			mui.alert("安装更新失败[" + e.code + "]：" + e.message)
			Common.setlocalStorage('isDownloadingNewApp', null); //设置正在下载的标志
		});
	},
	logOut: function() { //统一退出接口
		setTimeout(function() {
			if (window.plus) {
				plus.navigator.setStatusBarBackground('rgba(0,0,0,0)');
			}
		}, 300)
		window.clicked('../login.html?clear=true');
	},
	notlogin: function(page) {
		Common.tipMsg("您还未登录", "温馨提示", function() {
			Common.logOut();
		});
	},
	getlocalStorage: function(key) {
		try {
			var val = myStorage.getItem(key);
			val = unescape(val);
			if (val == "null") {
				return '';
			}
			return (val != 'undefined' ? val : '');
		} catch (e) {
			var val = unescape(window.localStorage[key]);
			if (val == "null") {
				return '';
			}
			return (val != 'undefined' ? val : '');
		}
	},
	setlocalStorage: function(key, val) {
		try {
			val = (val != 'undefined' ? val : '');
			myStorage.setItem(key, escape(val));
		} catch (e) {
			val = (val != 'undefined' ? val : '');
			window.localStorage.setItem(key, escape(val));
		}
	},
	toastTimeOut: undefined,
	toast: function(msg, duration) {
		duration = duration? duration : 2000;
		uni.showToast({
			icon: 'none',
			position: 'bottom',
			title: msg,
			duration:duration
		});
	},
	ClosePopupWithoutAction: function() { //不执行回调方法的关闭对话框
		Common.ClosePopupNoAction = true;
		mui.closePopups();
		if (MsgDialog)
			MsgDialog.close();
		setTimeout(function() {
			Common.ClosePopupNoAction = false;
		}, 100);
	},
	confirm: function(msg, title, btn, cellbackFun) { //确认窗口同一控制
		var newCellBackFun = function(e) {
			console.log(Common.ClosePopupNoAction);
			if (Common.ClosePopupNoAction) { //通过代码关闭对话框时，不往下执行;
				console.log('Popup Close No Action')
				Common.ClosePopupNoAction = false;
				return;
			} else
				cellbackFun(e);
		};

		uni.showModal({
			title: title,
			content: msg,
			success: function (res) {
				if (res.confirm) {
					console.log('用户点击确定');
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});

		mui.confirm(msg, title, btn, newCellBackFun, 'div');
	},
	GetRequest: function(href) {
		var url = decodeURIComponent(location.search); //获取url中"?"符后的字串

		if (href) {
			var param = href.split('?');
			if (param.length == 2) {
				url = ('?' + param[1]);
			}
		}
		var theRequest = new Object();
		if (url.indexOf("?") != -1) {
			var str = url.substr(1);
			strs = str.split("&");
			for (var i = 0; i < strs.length; i++) {
				theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
			}
		}
		return theRequest;
	},
	convertImgToBase64: function(url, callback, outputFormat) {
		var canvas = document.createElement('CANVAS'),
			ctx = canvas.getContext('2d'),
			img = new Image;

		img.crossOrigin = 'Anonymous';
		img.onload = function() {
			canvas.height = img.height;
			canvas.width = img.width;
			ctx.drawImage(img, 0, 0);
			var dataURL = canvas.toDataURL(outputFormat || 'image/png');
			callback.call(this, dataURL);
			canvas = null;
		};
		img.src = url;
	}
};

export default Common
